/**用户验证码 */
let userCheckCode = ''
function genDpop(url: string, method: string = 'POST') {
  const { privateKey, uuid, idToken } = getUserInfo()
  const { crv, kty, x, y, d } = privateKey

  const oHeader = {
    typ: 'dpop+jwt',
    alg: 'ES256',
    jwk: {
      crv,
      kty,
      x,
      y
    }
  }

  const oPayload = {
    // @ts-ignore
    iat: KJUR.jws.IntDate.get('now'),
    jti: idToken.jti,
    htu: url.split('?')[0],
    htm: method.toUpperCase(),
    uuid
  }

  const sHeader = JSON.stringify(oHeader)
  const sPayload = JSON.stringify(oPayload)
  // @ts-ignore
  const sKey = KEYUTIL.getKey({ kty: 'EC', d, x, y, crv: 'P-256' })
  // @ts-ignore
  const sResult = KJUR.jws.JWS.sign('ES256', sHeader, sPayload, sKey)
  console.log(`sResult ==>`, sResult)
  return sResult
}
function $fetch(param: { url: string; method?: 'GET' | 'POST'; data?: any }) {
  const { url, method = 'post', data } = param
  // 唐伟
  // const baseUrl = 'https://68m535x516.yicp.fun'
  // 线上
  const baseUrl = 'https://www.f2c.co.jp/api'
  const fetchOption = {
    method,
    headers: {
      'Content-Type': 'application/json'
    },
    body: method == 'post' ? JSON.stringify(data) : undefined
  }
  return new Promise<any>((resolve, reject) => {
    fetch(`${baseUrl}/${url}`, fetchOption)
      .then(response => response.json())
      .then(result => {
        const { code, msg } = result
        if (code == 200) {
          resolve(result)
        } else {
          sendMsgToPopup('open-modal', msg)
          reject({})
        }
      })
      .catch(e => {
        sendMsgToPopup('open-modal', e.message)

        reject({})
      })
  })
}
async function getDetail(list: any[]) {
  const targetList2 = []

  list = list.map((item: any, index: number) => {
    return {
      origin: { ...item },
      productPrice: item.price,
      item_id: JSON.parse(item.args).item_id,
      productName: item.name,
      thumbnails: item.thumbnails,
      index: index + 1,
      detail: {}
    }
  })
  // 循环查询详情
  for (const item of list) {
    const res = await request(
      `transaction_evidences/get?item_id=${item.item_id}&_datetime_format=U`
    )
    // 是否显示地址
    const { showable_address } = res.data
    // 有地址的才抓取
    if (showable_address === true) {
      const { data } = await request(`items/get?id=${item.item_id}`)
      item.description = data.description
      item.productTax = data.sales_fee.fee
      item.shipping_payer = data.shipping_payer.name
      item.status = res.data.status
      /*************************** seller(卖家信息) ******************************/
      let sellerInfo = {
        seller_shipping_fee: res.data.seller_shipping_fee
      }
      item.detail.seller = { ...data.seller, ...sellerInfo }
      /*************************** seller(卖家信息) ******************************/
      /*************************** buyer(买家信息) ******************************/
      let buyerInfo = {
        //购买时间
        // @ts-ignore

        purchaseDate: res.data.created,
        zipCode1: res.data.zip_code1,
        zipCode2: res.data.zip_code2,
        city: res.data.city,
        familyName: res.data.family_name,
        familyNameKana: res.data.family_name_kana,
        firstName: res.data.first_name,
        firstNameKana: res.data.first_name_kana,
        prefecture: res.data.prefecture,
        address1: res.data.address1,
        address2: res.data.address2,
        itemName: res.data.item_name,
        status: res.data.status,
        price: res.data.price,
        consumePoint: res.data.consume_point,
        consumeSales: res.data.consume_sales,
        paymentFee: res.data.payment_fee,
        paidPrice: res.data.paid_price
      }
      item.detail.buyer = { ...buyerInfo }
      /*************************** buyer(买家信息) ******************************/
      item.detail.origin = { ...res.data }
      sendMsgToPopup('set-progress', `${((item.index / list.length) * 100).toFixed(2)}%`)
      targetList2.push(item)
    }
  }
  sendMsgToPopup('set-progress', '100%')
  console.log(`targetList2 ==>`, targetList2)
  const { code, msg } = await $fetch({
    url: 'distribution/orderMercari/getInfoByHtml',
    data: {
      data: targetList2,
      checkCode: userCheckCode,
      shopName: getUserInfo().userName
    }
  })
  sendMsgToPopup('close-loading')
  alert(msg)
}

type IParams = {
  method?: 'get' | 'post'
  data?: object
}

const request = (url: string, params: IParams = { method: 'get' }) => {
  const { method, data } = params!
  const baseUrl = 'https://api.mercari.jp'

  const headers = new Headers()

  headers.append('Content-Type', 'application/json')
  headers.append('Accept-Language', 'ja')
  headers.append('Accept', 'application/json, text/plain, */*')
  headers.append('Authorization', getUserInfo().token)
  headers.append('Dpop', genDpop(baseUrl + '/' + url, method))
  headers.append(
    'User-Agent',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat'
  )
  headers.append('X-Platform', 'web')

  const requestOptions = {
    method,
    headers,
    body: method == 'post' ? JSON.stringify(data) : undefined
  }

  return new Promise<any>(resolve => {
    fetch(`${baseUrl}/${url}`, requestOptions)
      .then(res => res.json())
      .then(res => {
        console.log(`res ==>`, res)
        resolve(res)
      })
  })
}
/**
 * https://jp.mercari.com/todos
 * 获取取引中列表
 */
async function getList() {
  // 新逻辑
  const { data } = await request('services/todolist/v1/list', {
    method: 'post',
    data: {
      pageSize: 60
    }
  })
  getDetail(data)
}

const getUserInfo = () => {
  return {
    token: JSON.parse(localStorage.getItem('authTokenData') || '{}').accessToken,
    idToken: JSON.parse(localStorage.getItem('authTokenData') || '{}').idToken,
    dpop: JSON.parse(localStorage.getItem('authTokenData') || '{}').idTokenHint,
    userId: JSON.parse(localStorage.getItem('mercari.braze-agent.cache.user') || '{}').userId,
    uuid: JSON.parse(localStorage.getItem('uuid') || ''),
    privateKey: JSON.parse(localStorage.getItem('privateKey') || '{}'),
    userName: (document.querySelector('.merMenu') as any)?.innerText
  }
}

let get_user_name_timer: any
let get_user_name_time = 0
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  const { action, data } = request
  console.log(`content 收到消息 ==>`, request)
  switch (action) {
    case 'get-user-info' /**获取 用户信息 */:
      // 判断域名是否 location.origin==https://jp.mercari.com'
      if (location.origin != 'https://jp.mercari.com') {
        sendMsgToPopup(
          'bad-url',
          `请打开 <a target="_blank" class="underline" href="https://jp.mercari.com/">https://jp.mercari.com/</a> 登录,然后重试`
        )
        return
      }
      get_user_name_timer = setInterval(() => {
        console.log(`get_user_name_time ==>`, get_user_name_time)
        if (get_user_name_time >= 10) {
          clearInterval(get_user_name_timer)
          get_user_name_timer = null
          sendMsgToPopup('get-user-info-time-out')
          return
        }
        const username = (document.querySelector('.merMenu') as any)?.innerText
        console.log(`username ==>`, username)
        if (username) {
          sendMsgToPopup('get-user-info', getUserInfo())
          clearInterval(get_user_name_timer)
          get_user_name_timer = null
          get_user_name_time = 0
          return
        }
        get_user_name_time += 1
      }, 1000)
      break
    case 'get-list' /**获取 用户信息 */:
      userCheckCode = data
      getList()
      break
    default:
      break
  }
})

const sendMsgToPopup = (action: string, data?: any) => {
  chrome.runtime.sendMessage({
    from: 'content',
    to: 'popup',
    action,
    data
  })
}
